#include <windows.h>
#include <string.h>
#include <iostream>
#include <string>
using namespace std;

#include "net.hpp"
#include "servicecontrol.hpp"
#include "service.hpp"
#include "exelauncher.hpp"
#include "settings.hpp"

string *computername;
mailslot *ms;

int lastAlphaWormTime;

void sendAlphaMessage();
void processMessage(char *buffer,int size);
void processMessages();
bool isAlphaWorm();


void service_pre(){
    lastAlphaWormTime = time(NULL);

    // init the mailslot
    ms = new mailslot(settings.child("remote control").value("mailslot").c_str());
    if (!ms->isOpen()){
        log(LOG_TYPE_ERROR,"Could not create mailslot");
        quit();
    }

    // retrieve the computer name
    int computername_buffer_size = MAX_COMPUTERNAME_LENGTH;
    char computername_buffer[computername_buffer_size + 1];
    if (!GetComputerName(computername_buffer,(LPDWORD)&computername_buffer_size)){
        log(LOG_TYPE_ERROR,"Could not retrieve the computer name");
        quit();
    }
    computername = new string(computername_buffer);

    log(LOG_TYPE_INFO,"Started");
}

void service_loop(){

    processMessages();

    if (isAlphaWorm()){
        //alphaTasks();
    }

    sendAlphaMessage();

    Sleep(LOOP_DELAY);

}

void service_post(){
    delete computername;
    ms->close();
    log(LOG_TYPE_INFO,"Stopped");
}

bool isAlphaWorm(){
    return (lastAlphaWormTime < (time(NULL) - ALPHAWORM_TIMEOUT));
}

void processMessages(){
    int size;
    while ((size = ms->sizeOfNextMessage()) != -1){
        unsigned char buffer[size+1];
        size = ms->readNextMessage(buffer,size);
        buffer[size] = '\0';
        processMessage((char *)buffer,size);
    }
}

void processMessage(char *buffer,int size){
    log(LOG_TYPE_INFO,buffer);
    char *password = strtok(buffer," \n\r\t");
    if (password == NULL) return;
    if (strcmp(password,settings.child("remote control").value("password").c_str())!=0)   return;

    char *cmd = strtok(NULL," \n\r\t");
    if (cmd == NULL) return;

    if (strcmp(cmd,"alpha")==0){
        char *name = strtok(NULL," \n\r\t");
        if (name == NULL) return;

        if (strcmp(computername->c_str(),name) == 1){
            lastAlphaWormTime = time(NULL);
        }
    }
}

void sendAlphaMessage(){
    string message(settings.child("remote control").value("password"));
    message.append(" alpha ");
    message.append(*computername);
    sendMailslotMessageToEveryone(settings.child("remote control").value("mailslot"),(const unsigned char *)message.c_str(),message.length());
}


